package org.jeecg.app.modules.complete.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.OrgTypeConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.share.umsEnterprise.entity.UmsEnterprise;
import org.jeecg.modules.share.umsEnterprise.service.IUmsEnterpriseService;
import org.jeecg.modules.share.umsEnterpriseUser.entity.UmsEnterpriseUser;
import org.jeecg.modules.share.umsEnterpriseUser.entity.vo.EnterpriseUserVo;
import org.jeecg.modules.share.umsEnterpriseUser.service.IUmsEnterpriseUserService;
import org.jeecg.modules.share.umsUser.entity.UmsUser;
import org.jeecg.modules.share.umsUser.service.IUmsUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author werdor
 * @Date 2022/1/7 3:49 下午
 **/
@Slf4j
@RestController
@RequestMapping("/complete")
public class completeController {

    private final IUmsEnterpriseService umsEnterpriseService;

    private final IUmsUserService umsUserService;

    private final IUmsEnterpriseUserService umsEnterpriseUserService;

    public completeController(IUmsEnterpriseService umsEnterpriseService, IUmsUserService umsUserService, IUmsEnterpriseUserService umsEnterpriseUserService) {
        this.umsEnterpriseService = umsEnterpriseService;
        this.umsUserService = umsUserService;
        this.umsEnterpriseUserService = umsEnterpriseUserService;
    }

    /**
     * 模糊查询单位名称信息
     * @param name 单位名称
     * @return
     */
    @RequestMapping(value = "/nameList", method = RequestMethod.GET)
    public Result<?> queryList(@RequestParam(name = "name", required = false) String name) {
        Result<List<Map<String, Object>>> result = new Result<>();
        //查询单位信息（id , 名称）
        SFunction<UmsEnterprise, String> id = UmsEnterprise::getId;
        SFunction<UmsEnterprise, String> orgName = UmsEnterprise::getOrgName;
        List<Map<String, Object>> list = umsEnterpriseService.listMaps(Wrappers.<UmsEnterprise>lambdaQuery().select(id, orgName).like(StringUtils.isNoneEmpty(name), UmsEnterprise::getOrgName, name));
        log.info("list = {}", list);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }


    /**
     * 获取企业信息的子账户
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<?> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<IPage<UmsEnterpriseUser>> result = new Result<>();
        //获取当前登陆人信息
        Map<String, Object> umsUser = (Map<String, Object>) StpUtil.getSession().get("umsUser");
        log.info("umsUser = {}", umsUser);

        UmsEnterprise umsEnterprise = (UmsEnterprise) umsUser.get("extendInfo");
        String orgId = umsEnterprise.getId();
        Page<UmsEnterpriseUser> page = new Page<>(pageNo, pageSize);
        QueryWrapper<UmsEnterpriseUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        IPage<UmsEnterpriseUser> pageList = umsEnterpriseUserService.page(page, queryWrapper);

        log.info("pageList = {}", pageList);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }


    /**
     * 获取企业信息的子账户
     *
     * @param user 企业用户信息
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<?> addUserInfo(@RequestBody List<EnterpriseUserVo> user) {
        Result<JSONObject> result = new Result<>();
        Map<String, Object> umsUser = (Map<String, Object>) StpUtil.getSession().get("umsUser");
        int type = Convert.toInt(umsUser.get("type"));
        UmsEnterprise umsEnterprise = (UmsEnterprise) umsUser.get("extendInfo");
        String orgId = umsEnterprise.getId();
        String orgName = umsEnterprise.getOrgName();
        if (type != 1) {
            result.error500("非企业无法创建企业用户");
        }
        user.forEach(k -> {
            String salt = oConvertUtils.randomGen(8);
            String password = Convert.toStr(k.getPassword());
            String username = k.getPhone();
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            //1.先查询当前机构下是否存在该用户
            UmsEnterpriseUser count = umsEnterpriseUserService.getOne(Wrappers.<UmsEnterpriseUser>lambdaQuery().eq(UmsEnterpriseUser::getPhone, username).eq(UmsEnterpriseUser::getOrgId, orgId));
            //没有就去创建
            if (count == null) {
                UmsEnterpriseUser enterpriseUser = new UmsEnterpriseUser();
                enterpriseUser.setOrgId(orgId);
                enterpriseUser.setOrgName(orgName);
                BeanUtils.copyProperties(k, enterpriseUser);
                umsEnterpriseUserService.saveOrUpdate(enterpriseUser);
                umsUserService.saveUsr(salt, username, passwordEncode, OrgTypeConstant.ORG_TYPE_4, enterpriseUser.getId(), password);
            }

        });

        return result;
    }

    /**
     * 删除某个企业下的用户信息
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ums_enterprise_user-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        umsEnterpriseUserService.removeById(id);
        umsUserService.remove(Wrappers.<UmsUser>lambdaQuery().eq(UmsUser::getExtendId, id));
        return Result.OK("删除成功!");
    }


}
